package com.doudou.pay.helper.websocket;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.doudou.pay.helper.commons.JsonResult;
import com.doudou.pay.helper.entities.PayUser;
import com.doudou.pay.helper.entities.UserInfo;
import com.doudou.pay.helper.entities.UserPay;
import com.doudou.pay.helper.server.protoco.ProtocoConsts;
import com.doudou.pay.helper.service.PayService;
import com.doudou.pay.helper.service.PayUserService;

@Component
public class PayWebsocketHandler extends TextWebSocketHandler{
	
	private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<String, WebSocketSession>();
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private PayUserService payUserService;
	
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
		
		JsonResult jsonResult = new JsonResult();
		try {
			List<PayUser> payUsers = payUserService.getPayUserByUserId(userInfo.getUserId());
			if(null == payUsers || payUsers.size() == 0) {
				jsonResult.setDefine("不存在的用户");
				session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
				return;
			}
			
			//判断在线客户端数量
			Map<String, Integer> onlineClientMap = payUserService.getOnlineAuthToken(userInfo.getUserId());
			if(onlineClientMap.size() == 0) {
				jsonResult.setDefine("客户端不在线");
				session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
			}
			
			UserPay userPay = JSON.parseObject(message.getPayload(), UserPay.class);
			if(StringUtils.isEmpty(userPay.getType())) {
				jsonResult.setDefine("请选择支付方式");
				session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
				return;
			}
			
			if(userPay.getMoney() <= 0) {
				jsonResult.setDefine("请输入金额");
				session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
				return;
			}
			
			userPay.setUserId(userInfo.getUserId());
			userPay.setSessionKey(userInfo.getSessionKey());
			
			jsonResult.setCode(ProtocoConsts.SUCCESS)
					  .setDefine(ProtocoConsts.SUCCESS_DEFINE)
					  .setResult(payService.pay(userPay,onlineClientMap));
			session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setDefine("请选择支付方式与输入金额");
			session.sendMessage(new TextMessage(JSON.toJSONString(jsonResult)));
			return;
		}
		
	}
	
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		UserInfo authToken = (UserInfo) session.getAttributes().get("userInfo");
		this.sessionMap.put(authToken.getSessionKey(), session);
		super.afterConnectionEstablished(session);
	}
	
	@Override   
	public void handleTransportError(WebSocketSession session, Throwable thrwbl) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
		this.sessionMap.remove(userInfo.getSessionKey());
		if(session.isOpen()){           
			session.close();       
		}
		System.out.println("websocket connection closed......");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
		this.sessionMap.remove(userInfo.getSessionKey());
		super.afterConnectionClosed(session, status);
	}
	
	public void sendTextMsg(String sessionKey,String msgText) {
		try {
			WebSocketSession session = this.sessionMap.get(sessionKey);
			if(null != session) {
				System.out.println("回写支付响应信息:" + msgText);
				session.sendMessage(new TextMessage(msgText.getBytes()));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
